package com.kdtech.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ZipUtils {
	
	private static final String charset = "UTF-8";
	 
	/**
	* 使用gzip进行压缩
	*/
	public static String gzip(String primStr) {
		if (primStr == null || primStr.length() == 0) {
			return primStr;
		}
		ByteArrayOutputStream out = null;
		String gzipStr = "";
		try {
			out = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			gzip.write(primStr.getBytes(charset));
			gzip.close();
			gzipStr = out.toString("ISO-8859-1");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return gzipStr;
	}
	
	/**
	*
	* <p>Description:使用gzip进行解压缩</p>
	* @param compressedStr
	* @return
	*/
	public static String gunzip(String compressedStr) {
		if (compressedStr == null || compressedStr.length() == 0) {   
			return compressedStr;   
		}   
	    ByteArrayOutputStream out = null;
	    ByteArrayInputStream in = null;
	    GZIPInputStream gunzip = null;
	    String gunzipStr = "";
	    try {
		    out = new ByteArrayOutputStream();   
		    in = new ByteArrayInputStream(compressedStr.getBytes("ISO-8859-1"));   
		    gunzip = new GZIPInputStream(in);   
		    byte[] buffer = new byte[1024];   
		    int n;   
		    while ((n = gunzip.read(buffer)) >= 0) {
		      out.write(buffer, 0, n);   
		    }
		    gunzipStr = out.toString(charset);
	    } catch(IOException e) {
	    	e.printStackTrace();
	    } finally {
	    	if(null != gunzip) {
	    		try {
					gunzip.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	    	}
	    	if(null != in) {
	    		try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	    	}
	    }
	    // toString()使用平台默认编码，也可以显式的指定如toString(&quot;GBK&quot;)  
	    return gunzipStr;   
	}
	
	public static void main(String[] args) {
		String str = "پۇل مۇئامىلە با";
		System.out.println(str.equals(gunzip(gzip(str))));
	}
}
